package org.windowkit.toolkit.print;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;

import javax.swing.JComponent;
import javax.swing.JTable;

/**
 * @author Eric Lundin
 *
 */
public class DefaultPrinter extends AbstractPrinter {

	/**
	 * Create a table printer.
	 *
	 * @param component
	 *            The component to print
	 * @param componentHeader
	 *            The header for this component.
	 */
	public DefaultPrinter(final JComponent component, final JComponent componentHeader,
			final String title) {
		super(component, componentHeader, title);
		setHeightIncrement(((JTable) component).getRowHeight());
	}

	/*
	 * (non-Javadoc)
	 */
	@Override
	protected void paintPage(final PageFormat pageFormat, final int pageIndex, final Graphics2D g2) {
		int xTranslateCells;
		int yTranslateCells;
		double xTranslateAmount;
		double yTranslateAmount;

		// Determine the "cell" this page represents in the full image grid.
		xTranslateCells = pageIndex % getPagesWide(pageFormat);
		yTranslateCells = (int) Math.floor(pageIndex / getPagesWide(pageFormat));

		xTranslateAmount = (-xTranslateCells) * pageFormat.getImageableWidth();
		yTranslateAmount = -yTranslateCells * getYCellHeight(pageFormat, g2);

		g2.translate(pageFormat.getImageableX() + xTranslateAmount, pageFormat
				.getImageableY());

		g2.setColor(Color.BLACK);
		g2
				.drawString(
						getTitle(),
						(int) (g2.getClipBounds().getCenterX() - (getTitleDimensions(g2).width / 2)),
						getTitleDimensions(g2).height);
		g2.translate(0L, getTitleDimensions(g2).height
				+ getStringPadding(Y_AXIS));
		if (header != null) {
			header.paint(g2);
		}

		g2.translate(0L, yTranslateAmount + headerHeight);
		g2
				.setClip(
						g2.getClipBounds().x,
						(int) (g2.getClipBounds().y + headerHeight
								+ getStringPadding(Y_AXIS) + getTitleDimensions(g2).height),
						g2.getClipBounds().width, (int) getYCellHeight(
								pageFormat, g2));
		component.paint(g2);
		g2
				.setClip(g2.getClipBounds().x, g2.getClipBounds().y, g2
						.getClipBounds().width, ((int) getYCellHeight(
						pageFormat, g2) + getPageMessageDimensions(g2).height));
		g2
				.drawString(
						createPageNumberString(pageIndex,
								getTotalNumberOfPages(pageFormat,g2)),
						(int) g2.getClipBounds().getCenterX()
								- ((getPageMessageDimensions(g2).width / 2)),
						(int) (g2.getClipBounds().y
								+ getYCellHeight(pageFormat, g2) + getPageMessageDimensions(g2).height));

	}

}
